package com.xiaoq.shop.service.impl;

import com.xiaoq.shop.entity.SimpleLock;
import com.xiaoq.shop.repository.ISimpleLockRepository;
import com.xiaoq.shop.service.ISimpleLockService;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by chenjh on 2017/12/1.
 */
@Service
public class SimpleLockServiceImpl implements ISimpleLockService {

    @Autowired
    private ISimpleLockRepository simpleLockRepository;

    @Override
    public boolean save(SimpleLock simpleLock) {
        return simpleLockRepository.save(simpleLock);
    }

    @Override
    public boolean lock(String targetId) {
        if(StringUtils.isBlank(targetId)){
            return false;
        }
        DateTime dateTime = new DateTime();
        SimpleLock simpleLock = new SimpleLock();
        simpleLock.setTargetId(targetId);
        //锁定1分钟
        simpleLock.setLockExpireTime(dateTime.plusMinutes(1).getMillis());
        return simpleLockRepository.lock(simpleLock);
    }

    @Override
    public boolean releaseLock(String couponId) {
        if(StringUtils.isBlank(couponId)){
            return false;
        }
        SimpleLock simpleLock = new SimpleLock();
        simpleLock.setTargetId(couponId);
        return simpleLockRepository.releaseLock(simpleLock);
    }
}
